package com.orcwar.gui.activities;

import java.io.IOException;
import java.io.InputStream;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.orcwar.R;
import com.orcwar.ai.OWAI;
import com.orcwar.ai.naive.NaiveAI;
import com.orcwar.controller.OWController;
import com.orcwar.engine.OWConstants;
import com.orcwar.engine.OWGame;
import com.orcwar.engine.randomizer.OWOrcNameRandomizer;
import com.orcwar.gui.OWGUI;
import com.orcwar.gui.OWGUIDrawer;
import com.orcwar.gui.views.OWBottomMenuView;
import com.orcwar.gui.views.OWCanvasView;
import com.orcwar.gui.views.OWJournalView;
import com.orcwar.thread.MainThread;
import com.orcwar.util.BitmapUtil;
import com.orcwar.util.MetricsUtil;

public class GameActivity extends Activity {

	/** The game engine. */
	private OWGame game;

	/**
	 * The GUI manager.
	 */
	private OWGUI gui;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		BitmapUtil.initialize(getResources());
		MainThread thread = new MainThread(this);		
		
		// build game
		game = OWGame.getInstance(thread);
		// build controller
		OWController controller = new OWController(game, game.userPlayer);
		// build GUI manager
		gui = new OWGUI(this, controller);
		
		controller.setGui(gui);
		thread.setGui(gui);
		game.addGameListener(gui);
		
		// init the AI
		OWAI ai = new NaiveAI(game, game.aiPlayer);
		game.addGameListener(ai);

		// Set fullscreen and remove the title bar
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON,
				WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

		setContentView(R.layout.activity_main);
		LinearLayout mainLayout = (LinearLayout) findViewById(R.id.mainLayout);

		DisplayMetrics metrics = new DisplayMetrics();
		((WindowManager) getSystemService(Context.WINDOW_SERVICE))
				.getDefaultDisplay().getMetrics(metrics);
		int w = metrics.widthPixels;
		int h = metrics.heightPixels - OWConstants.BOTTOM_MENU_HEIGHT;
		
		MetricsUtil.initialize(metrics);
		
		
		View gameView = new OWCanvasView(this, gui);
		
		//absolute layout to put the gamewindow and the journal
		RelativeLayout relativeLayout = new RelativeLayout(this);
		
		RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(w, h);
		params.leftMargin = 0;
		params.topMargin = 0;
		relativeLayout.addView(gameView, params);
		
		RelativeLayout.LayoutParams params2 = new RelativeLayout.LayoutParams(w, 100);
		params2.leftMargin = 10;
		params2.topMargin = MetricsUtil.getGameWindowHeight() - 110;
		OWJournalView journalView = new OWJournalView(this);
		game.addGameListener(journalView);
		relativeLayout.addView(journalView, params2);
		
		mainLayout.addView(relativeLayout, w, h);
		
		//Inflate the bottom menu
		getLayoutInflater().inflate(R.layout.bottom_menu, mainLayout);
		OWBottomMenuView bottomMenu = null;
		for (int i=0 ; i<mainLayout.getChildCount() ; i++) {
			if (mainLayout.getChildAt(i) instanceof OWBottomMenuView) {
				bottomMenu = (OWBottomMenuView) mainLayout.getChildAt(i);
				break;
			}
		}
		bottomMenu.initialize(gui);
		
		// init the DRAWER
		OWGUIDrawer.initialize(game, gui, controller);
		
		//Init name randomizer
		InputStream is = getResources().openRawResource(R.raw.syllables);
		OWOrcNameRandomizer.initiliaze(is);
		try {
			is.close();
		} catch (IOException e) {
			Log.e(this.getClass().getSimpleName(), "Failed to close the syllables.txt file");
		}
		
		game.start();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		game.pause();

		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.layout.menu, menu);
		return true;
	}

	@Override
	public boolean onMenuOpened(int featureId, Menu menu) {
		game.pause();
		return true;
	}

	@Override
	public void onOptionsMenuClosed(Menu menu) {
		game.unpause();
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.m_endTurn:
			gui.pass();
			return true;
		case R.id.m_test:
			startActivity(new Intent(this, OWCharacterSelectActivity.class));
			return true;
		default:
			// return false;
		}

		return true;
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (OWConstants.DEBUG) {
			Log.d(this.getClass().getName(), "Touch pressed : " + keyCode);
		}
		switch (keyCode) {
		case KeyEvent.KEYCODE_BACK:
			exitApplication();
			break;
		case KeyEvent.KEYCODE_MENU:
			// Menu button
		default:
			break;
		}
		return false;
	}

	/**
	 * Kill the application
	 */
	protected void exitApplication() {
		game.leaveGame();
		finish();
		System.gc();
		android.os.Process.killProcess(android.os.Process.myPid());
	}

	@Override
	protected void onStart() {
		super.onStart();
	}

	@Override
	protected void onStop() {
		super.onStop();
	}

	@Override
	protected void onResume() {
		super.onResume();
		game.unpause();
	}

	@Override
	protected void onPause() {
		super.onPause();
		game.stop();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		OWGame.getInstance().leaveGame();
		Log.i("Orcwar", "DESTROY");
		exitApplication();
	}

}
